package com.nce.util;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;

public class MyLoginUrlAuthenticationEntryPoint extends
		LoginUrlAuthenticationEntryPoint {

	public void commence(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException authException)
			throws IOException, ServletException {
		String returnUrl = buildHttpReturnUrlForRequest(request);
		request.getSession().setAttribute("ru", returnUrl);
		if (isUseForward()) {
			request.getSession().setAttribute("isUseForward", "yes");
		}
		super.commence(request, response, authException);
	}

	protected String buildHttpReturnUrlForRequest(HttpServletRequest request)
			throws IOException, ServletException {

		String scheme = "http";
		String serverName = request.getServerName();
		int port = request.getServerPort();
		String contextPath = request.getContextPath();
		String servletPath = request.getServletPath();
		String pathInfo = request.getPathInfo();
		String query = request.getQueryString();

		StringBuilder sb = new StringBuilder();
		if (!isUseForward()) {
			sb.append(scheme).append("://").append(serverName);
			// Append the port number if it's not standard for the scheme
			if (port != (scheme.equals("http") ? 80 : 443)) {
				sb.append(":").append(Integer.toString(port));
			}
			if (contextPath != null) {
				sb.append(contextPath);
			}
		}
		
		if (servletPath != null) {
			sb.append(servletPath);
		}
		if (pathInfo != null) {
			sb.append(pathInfo);
		}
		if (query != null) {
			sb.append("?").append(query);
		}

		return sb.toString();
	}

}
